import React, { Component } from 'react';
import {View, Image, Picker, Text} from "@tarojs/components";
import {REPORT_ESTIMATED_EARNINGS_DATA, RESOURCE_URL} from '../../../constants/api';
import GzhAuth from '../../../components/gzh-auth/gzh-auth';
import {http} from '../../../utils/http';
import {h5Wx} from '../../../utils/h5.service';
import {GetRequest, vcmonitor} from "../../../utils/tools";
import "./estimatedIncome.scss";

export default class Member extends Component {
  state: {
    info: any
    listInfo: any
    // Tab 激活状态
    active: number
    // 日报
    day_date: string
    // 月报
    month_date: string
    // 自定义 起始时间
    show: boolean
    start_date: string
    end_date: string
    // 右侧显示的文本
    date_right: string
  } = {
    info: {
      time: '',
      num: 0,
    },
    listInfo: [],
    // Tab 激活状态
    // 1:日报 2:月报 3:自定义
    active: 1,
    // 日报
    day_date: "",
    // 月报
    month_date: "",
    // 自定义 起始时间
    show: false,
    start_date: "起始时间",
    end_date: "终止时间",
    // 右侧显示的文本
    date_right: "2021/10/01",
  };

  async componentDidShow() {
    vcmonitor(this)
    if (process.env.TARO_ENV === "h5") {
      await h5Wx.getConfig();
    }
    // 获取当前时间戳 转换为 2021/10/01 格式
    const date = new Date();
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    month = +month;
    day = +day;
    month = month >= 10 ? month : "0" + month;
    day = day >= 10 ? day : "0" + day;
    let temp = "";
    temp = year + "/" + month + "/" + day;
    this.setState({date_right: temp});
    // 时间格式转换成-
    temp = this.timeFormatConversion(temp);
    await this.setStateSync({day_date: temp});
    // 设置默认 起始时间
    await this.setState({start_date: temp, end_date: temp});

    // 设置默认 年月
    await this.setState({month_date: temp.slice(0, 7)});
    const {search_date_start = '', search_date_end = '', search_month = '', active = 0} = Taro.getCurrentInstance().router.params
    if (active == 1) {
      await this.setStateSync({day_date: search_date_start, date_right: search_date_start})
    } else if (active == 2) {
      await this.setStateSync({month_date: search_month, date_right: search_month})
    } else if (active == 3) {
      await this.setStateSync({show: true, start_date: search_date_start, end_date: search_date_end})
    }
    await this.setStateSync({active: +active})
    // 获取 数据总览
    this.getDataOverView();
  }

  // 获取 数据总览
  async getDataOverView() {
    const {start_date, day_date, month_date, end_date, active} = this.state
    const tempObj = {};
    if (active == 1) {
      tempObj.search_date_start = day_date;
      tempObj.search_date_end = day_date;
    } else if (active == 2) {
      tempObj.search_month = month_date;
    } else if (active == 3) {
      tempObj.search_date_start = start_date;
      tempObj.search_date_end = end_date;
    }
    const res = await http.HGet(REPORT_ESTIMATED_EARNINGS_DATA, tempObj);
    if (res) {
      this.setState({listInfo: res.data.list, info: res.data});
    }
  }

  // 日报
  async bindDayDateChange(e) {
    await this.setStateSync({active: 1});
    await this.setStateSync({day_date: e.detail.value});
    this.setState({show: false});
    this.setState({date_right: e.detail.value.split("-").join("/")});

    // 获取 数据总览
    this.getDataOverView();
  }

  // 月报
  async bindMonthDateChange(e) {

    await this.setStateSync({active: 2});
    await this.setStateSync({month_date: e.detail.value});
    this.setState({show: false});
    this.setState({date_right: e.detail.value.split("-").join("/")});

    // 获取 数据总览
    this.getDataOverView();
  }

  // 起
  async bindStartDateChange(e) {

    await this.setStateSync({start_date: e.detail.value});
    this.setState({date_right: "全部"});
    // 获取 数据总览
    this.getDataOverView();
  }

  // 止
  async bindEndDateChange(e) {
    await this.setStateSync({end_date: e.detail.value});
    this.setState({date_right: "全部"});
    // 获取 数据总览
    this.getDataOverView();
  }

  // 点击 切换 Tabs active
  async activeTabs(num) {
    await this.setStateSync({active: num})
    if (num == 1) {
      let temp = this.state.day_date
      if (temp.indexOf('-')) {
        temp = this.timeFormatConversionElse(temp)
      }
      this.setState({date_right: temp})
    }
    if (num == 2) {
      let temp = this.state.month_date
      if (temp.indexOf('-')) {
        temp = this.timeFormatConversionElse(temp)
      }
      this.setState({date_right: temp})
    }
    // 显示 自定义 日期区间选择器
    if (num == 3 && this.state.show == false) {
      this.setState({show: true});
    } else {
      this.setState({show: false});
    }
    // 获取 数据总览
    this.getDataOverView();
  }

  // 时间格式转换  /转-
  timeFormatConversion(str) {
    return str.split("/").join("-");
  }

  // 时间格式转换  -转/
  timeFormatConversionElse(str) {
    return str.split("-").join("/");
  }

  // setState 异步转同步
  setStateSync(state) {
    return new Promise(resolve => {
      this.setState(state, resolve);
    });
  }

  render() {
    const {
      listInfo,
      info,
      active,
      show,
      start_date,
      end_date,
      date_right,
    } = this.state;

    return (
      <View className='report'>
        <GzhAuth />
        <View className='report-wrapper'>
        <View className='select-time'>
          <View className='left flex-row'>
            <View
              className={`mar-right ${active === 1 ? "tab-active" : "tab-no-active"
              }`}
              onClick={this.activeTabs.bind(this, 1)}
            >
              <View>日报</View>
            </View>
            <View
              className={`mar-right ${active === 2 ? "tab-active" : "tab-no-active"
              }`}
              onClick={this.activeTabs.bind(this, 2)}
            >
              <View>月报</View>
            </View>
            <View
              className={`${active === 3 ? "tab-active" : "tab-no-active"
              }`}
              onClick={this.activeTabs.bind(this, 3)}
            >
              <View>自定义</View>
            </View>
          </View>
          {/* 右侧的 picker 组 */}
          <View className='right'>
            {/* 年 月 日 */}
            {active == 1 ? (
              <View className='section'>
                <Picker
                  mode='date'
                  value='{day_date}'
                  start='1970-01-01'
                  end='2050-01-01'
                  onChange={this.bindDayDateChange.bind(this)}
                >
                  {date_right}
                </Picker>
              </View>
            ) : (
              <View />
            )}
            {/* 年 月 */}
            {active == 2 ? (
              <View className='section'>

                <Picker
                  mode='date'
                  value='{month_date}'
                  start='1970-01-01'
                  end='2050-01-01'
                  fields='month'
                  onChange={this.bindMonthDateChange.bind(this)}
                >
                  {date_right}
                </Picker>
              </View>
            ) : (
              <View />
            )}
            {/* 自定义 不显示右侧 picker  */}
            {active == 3 ? (
              <View />
            ) : (
              <Image
                className='arrow-right-image-rotate'
                src='https://resource.ivcheng.com/resources/images/arrow-right.png'
              />
            )}
          </View>
        </View>
        {/* 自定义 日期区间选择器 */}
        {!show ? (
          <View />
        ) : (
          <View className='select-time-start-end'>
            <View className='item'>
              <Picker
                mode='date'
                value='{start_date}'
                start='1970-01-01'
                end='2050-01-01'
                onChange={this.bindStartDateChange.bind(this)}
              >
                <View className='pickerr'>{start_date}</View>
              </Picker>
            </View>
            <View style='color: #666;'>—</View>
            <View className='item'>
              <Picker
                mode='date'
                value='{end_date}'
                start='1970-01-01'
                end='2050-01-01'
                onChange={this.bindEndDateChange.bind(this)}
              >
                <View className='pickerr'>{end_date}</View>
              </Picker>
            </View>
          </View>
        )}
        </View>
        <View className='center-data'>
          <View className='center-data-num'>{ info.estimatedEarnings || 0 }</View>
          <View className='center-data-tip'>预估收益（元）</View>
          <View className='center-data-time'>数据更新时间：{ info.now_time || '' }</View>
        </View>
        {listInfo && listInfo.length > 0 && <View className='data-all'>
          <View className='big-title'><Text>收益明细</Text></View>
          {listInfo.map((item, index) =>
            <View className='list-items' key={index}>
              <View className='top-title'>
                <View className='left-title'>{item.product_name}</View>
                <View className={`right-num ${item.status ===4 && 'lessZero'}`}>{item.status_str}{item.total_amount}</View>
              </View>
              <View className='center-time'>
                <View className='left-time'>{item.offpay_date}</View>
                <View className='right-status'>{item.status_name}</View>
              </View>
            </View>
          )}
        </View>}
        {listInfo.length <= 0 && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/upload/images/20211112/1636708674979_153.png`} mode='widthFix' />
          <View className='text'>暂无数据</View>
        </View>}
        <View style='height: 30px;'></View>
      </View>
    );
  }
}
